//
//  MahjongMainVC.m
//  Mahjong
//
//  Created by 饶首建 on 17/6/29.
//  Copyright © 2017年 com.ikamobile.com. All rights reserved.
//

#import "MahjongMainVC.h"
#import "MahjongLoginVC.h"

#import "MahjongGameCVC.h"
#import "ChartHeaderView.h"
#import "ResultTableViewCell.h"
#import "HWPopTool.h"
#import "MahjongControlView.h"
#import "MahjongDataView.h"
#import "MahjongRecordView.h"
#import "MahjongMachineView.h"
#import "MahjongLogoutView.h"
#import "MahjongAlertView.h"

#import "GameModel.h"
#import "PatternModel.h"
#import "ActionModel.h"



@interface MahjongMainVC () <UICollectionViewDelegate,UICollectionViewDataSource>

@property (weak, nonatomic) IBOutlet UILabel *networkLabel;
@property (weak, nonatomic) IBOutlet UILabel *baseAndCeilingLabel;
@property (weak, nonatomic) IBOutlet UILabel *ruleLabel;
@property (weak, nonatomic) IBOutlet UILabel *gameIndexLabel;
@property (weak, nonatomic) IBOutlet UIButton *gangBtn;
@property (weak, nonatomic) IBOutlet UIButton *huBtn;
@property (weak, nonatomic) IBOutlet UIButton *chaBtn;

@property (weak, nonatomic) IBOutlet UIButton *logoutBtn;
@property (weak, nonatomic) IBOutlet UIButton *recordBtn;
@property (weak, nonatomic) IBOutlet UIButton *dataBtn;
@property (weak, nonatomic) IBOutlet UIButton *controlBtn;
@property (weak, nonatomic) IBOutlet UIButton *gameBtn;

@property (weak, nonatomic) IBOutlet UICollectionView *gameCollectionView;
@property (nonatomic,strong) UITableView *controlTableView;
@property (nonatomic,strong) UITableView *resultTableView;

@property (nonatomic,strong) NSMutableArray *gameArr;
@property (nonatomic,assign) NSInteger indexOfGame;
@property (nonatomic,assign) NSInteger indexOfNewGame;

@property (nonatomic,strong) ChartHeaderView *chartHeaderView;

@property (nonatomic,assign) CGFloat modalViewW;
@property (nonatomic,assign) CGFloat modalViewH;

@property (nonatomic,assign) ControlType controlType;
@property (nonatomic,strong) PatternModel *patternModel;
@property (nonatomic,strong) GameModel *currentGameModel;
@property (nonatomic,strong) ActionModel *selectedTagAction;

@property (nonatomic,strong) NSMutableArray *resultActionArr;

@property (nonatomic,strong) PlayerModel *owner;

@end

static NSString *kMahjongGameCVC = @"MahjongGameCVC";
static NSString *kResultTableViewCell = @"ResultTableViewCell";

@implementation MahjongMainVC

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(connectCallBack) name:NOTIFICATION_CONNECTED_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(errorCallBack) name:NOTIFICATION_ERROR_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(disConnectCallBack) name:NOTIFICATION_DISCONNECTED_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(newGameCallBack:) name:NOTIFICATION_NEWGAME_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(actionCallBack:) name:NOTIFICATION_ACTION_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(matchLeaveCallBack:) name:NOTIFICATION_MATCH_LEAVE_CALLBACK object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)loadGames{
    [GameModel gamesOfMatch:_matchModel.matchId success:^(id array) {
        [_gameArr removeAllObjects];
        [_gameArr addObjectsFromArray:array];
        
        if (_gameArr.count) {
            _indexOfGame = _gameArr.count - 1;
            _gameIndexLabel.text = NSStringFormat(@"第%ld局",_indexOfGame+1);
            _currentGameModel = _gameArr[_indexOfGame];
        }else{
            _gameIndexLabel.text = @"没有新局";
        }
        
        [_gameCollectionView reloadData];
        if (_gameArr.count) {
            [_gameCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_indexOfGame inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
        }
    } fail:^(NSString *errorStr) {
        [Hud hudText:errorStr inView:self.view];
    }];
}

- (void)newGame{
    NSString *url = [BASE_URL stringByAppendingPathComponent:NSStringFormat(@"Matches/%@/games",_matchModel.matchId)];
    NSDictionary *param = @{};
    [HttpUtil sendRequestURL:url method:POST param:param success:^(id response) {
        
    } fail:^(NSString *errorStr) {
        [Hud hudText:errorStr inView:self.view];
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initData];
    [self initUI];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

    [PatternModel loadPatternDataSuccess:^(id model) {
        _patternModel = model;
    } fail:^(NSString *errorStr) {}];
    
    [self loadGames];
}

- (void)initData{
    _owner = [[PlayerModel alloc]init];
    _owner.playerId = [PlayerModel ownerInstance].playerId;
    _owner.playerName = [PlayerModel ownerInstance].playerName;
    
    _gameArr = [NSMutableArray new];
}

- (void)initUI{
    [_gameCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([MahjongGameCVC class]) bundle:nil] forCellWithReuseIdentifier:kMahjongGameCVC];
    _modalViewW = SWidth() * 4/5;//modal 宽度
    _modalViewH = SHeight() * 4/5;//modal 高度
    
    NSMutableArray *tmp = [NSMutableArray new];
    [tmp addObjectsFromArray:_matchModel.rules];
    if (![tmp containsObject:@"自摸加番"]) {
        [tmp addObject:@"自摸加底"];
    }
    _ruleLabel.text = NSStringFormat(@"牌局规则:%@",[tmp componentsJoinedByString:@","]);
    _baseAndCeilingLabel.text = NSStringFormat(@"底:%ld 限番:%ld",_matchModel.base,_matchModel.ceiling);
    if (_matchModel.ceiling == 20) {
        _baseAndCeilingLabel.text = NSStringFormat(@"底:%ld 限番:%@",_matchModel.base,@"不限");
    }
}

#pragma mark - socket通知:GameCallBackDelegate
- (void)connectCallBack{
    _networkLabel.text = @"网络正常";
    _networkLabel.textColor = [UIColor whiteColor];
    [self loadGames];
}

- (void)errorCallBack{
    _networkLabel.text = @"连接出错";
    _networkLabel.textColor = UIColorHex(F15A5A);
}

- (void)disConnectCallBack{
    _networkLabel.text = @"连接已断开";
    _networkLabel.textColor = UIColorHex(F15A5A);
}

- (void)newGameCallBack:(NSNotification *)notification{
    NSDictionary *data = notification.object;
    data = [NSDictionary recursionResultJson4NullclassToNullstring:data];
    GameModel *mm = [GameModel gameModelPushParse:data];
    [_gameArr addObject:mm];
    if (_gameArr.count) {
        _indexOfNewGame = _gameArr.count - 1;
        _currentGameModel = _gameArr[_indexOfNewGame];
        _gameIndexLabel.text = NSStringFormat(@"第%ld局",_indexOfNewGame+1);
        
        [_gameCollectionView reloadData];
        [_gameCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_indexOfNewGame inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    }
}

- (void)actionCallBack:(NSNotification *)notification{
    NSDictionary *data = notification.object;
    data = [NSDictionary recursionResultJson4NullclassToNullstring:data];
    GameModel *returnGameModel = [GameModel gameModelPushParse:data];
    for (int i=0;i<_gameArr.count;i++) {
        GameModel *gm = _gameArr[i];
        if ([returnGameModel.gameId isEqualToString:gm.gameId]) {
            [_gameArr replaceObjectAtIndex:i withObject:returnGameModel];
            break;
        }
    }
    [_gameCollectionView reloadData];
}

- (void)matchLeaveCallBack:(NSNotification *)notification{
    NSDictionary *data = notification.object;
    data = [NSDictionary recursionResultJson4NullclassToNullstring:data];

    _gameBtn.enabled = NO;
    _gangBtn.enabled = NO;
    _huBtn.enabled = NO;
    _chaBtn.enabled = NO;
    
    [self disableSubView:_gameCollectionView];
    
    MahjongAlertView *view = [MahjongAlertView mahjongAlertView];
    view.textLabel.text = NSStringFormat(@"%@退出了\n牌局自动终止",data[@"player"][@"name"]);
    [self showModalWithView:view];
}

- (void)disableSubView:(UIView*)view{
    for (UIView* subView in view.subviews){
        if ([subView isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *)subView;
            btn.enabled = NO;
        }
        [self disableSubView:subView];
    }
}

#pragma mark - IBOutlet Action
- (IBAction)gangAction:(id)sender {
    MahjongControlView *view = [MahjongControlView mahjongControlView];
    view.matchModel = _matchModel;
    view.playersArr = _matchModel.others;
    view.gameModel = _currentGameModel;
    view.controlType = ControlTypeGang;
    view.owner = _owner;
    view.isEditAction = NO;
    view.dataArr = _patternModel.gangPatternArr;
    view.collectionView.contentInset = UIEdgeInsetsMake(100, 0, 0, 0);
    [self showModalWithView:view];
}

- (IBAction)huAction:(id)sender {
    MahjongControlView *view = [MahjongControlView mahjongControlView];
    view.matchModel = _matchModel;
    view.playersArr = _matchModel.others;
    view.gameModel = _currentGameModel;
    view.controlType = ControlTypeHu;
    view.owner = _owner;
    view.isEditAction = NO;
    view.dataArr = [_patternModel.huPatternArr arrayByAddingObjectsFromArray:_matchModel.optionalArr];
    [self showModalWithView:view];
}

- (IBAction)chaAction:(id)sender {
    MahjongControlView *view = [MahjongControlView mahjongControlView];
    view.matchModel = _matchModel;
    view.playersArr = _matchModel.others;
    view.gameModel = _currentGameModel;
    view.controlType = ControlTypeCha;
    view.owner = _owner;
    view.isEditAction = NO;
    NSMutableArray *tmp = [NSMutableArray new];
    for (NSString *str in _matchModel.optionalArr) {
        if ([_patternModel.optionalChaPatternArr containsObject:str]) {
            [tmp addObject:str];
        }
    }
    view.dataArr = [_patternModel.chaPatternArr arrayByAddingObjectsFromArray:tmp];
    [self showModalWithView:view];
}

- (IBAction)logoutAction:(id)sender {
    MahjongLogoutView *mahjongLogoutView = [MahjongLogoutView mahjongLogoutView];
    mahjongLogoutView.matchModel = _matchModel;
    mahjongLogoutView.gameArr = _gameArr;
    mahjongLogoutView.owner = _owner;
    mahjongLogoutView.gameModel = _gameArr.lastObject;
    mahjongLogoutView.logoutTapBlock = ^(){
        NSString *url = NSStringFormat(@"%@/Matches/%@/users/%@/leave",BASE_URL,_matchModel.matchId,_owner.playerId);
        [HttpUtil sendRequestURL:url method:POST param:@{} success:^(id response) {
            [[HWPopTool sharedInstance] closeWithBlcok:^{
                UIViewController *vc =self.presentingViewController;
                while (![vc isKindOfClass:[MahjongLoginVC class]]) {
                    vc = vc.presentingViewController;
                }
                [vc dismissViewControllerAnimated:YES completion:^{
                    
                }];
            }];
            
        } fail:^(NSString *errorStr) {
            [Hud hudText:errorStr inView:self.view];
        }];
    };
    
    [self showModalWithView:mahjongLogoutView];
}

- (IBAction)recordAction:(id)sender {
    MahjongRecordView *view = [MahjongRecordView mahjongRecordView];
    view.gameModel = _gameArr[_indexOfGame];
    view.owner = _owner;
    [view detailActionResult];
    [self showModalWithView:view];
}

- (IBAction)dataAction:(id)sender {
    MahjongDataView *dataView = [MahjongDataView mahjongDataView];
    if (!_chartHeaderView) {
        _chartHeaderView = [[ChartHeaderView alloc]initWithFrame:CGRectMake(0, 0, dataView.dataContainerView.frame.size.width, dataView.dataContainerView.frame.size.height) gameArr:_gameArr matchModel:_matchModel];
    }
    [_chartHeaderView updateChartGameArr:_gameArr matchModel:_matchModel];
    [dataView.dataContainerView addSubview:_chartHeaderView];
    [self showModalWithView:dataView];
}

- (IBAction)controlAction:(id)sender {
    MahjongMachineView *view = [MahjongMachineView mahjongMachineView];
    [self showModalWithView:view];
}
- (IBAction)newGameAction:(id)sender {
    MahjongMachineView *view = [MahjongMachineView mahjongMachineView];
    view.openOnce = YES;
    [self showModalWithView:view];
    [self newGame];
}

#pragma mark - private method

#pragma mark - 弹框
- (void)showModalWithView:(UIView*)view{
    view.layer.cornerRadius = 10.f;
    view.layer.masksToBounds = YES;
    [HWPopTool sharedInstance].shadeBackgroundType = ShadeBackgroundTypeGradient;
    [HWPopTool sharedInstance].closeButtonType = ButtonPositionTypeNone;
    [[HWPopTool sharedInstance] showWithPresentView:view animated:NO];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _gameArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MahjongGameCVC *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kMahjongGameCVC forIndexPath:indexPath];
    cell.owner = _owner;
    cell.gameModel = _gameArr[indexPath.row];
#pragma mark - 标签
    cell.getTagClickBlock = ^(id data){
        ActionModel *am = data;
        MahjongControlView *view = [MahjongControlView mahjongControlView];
        view.matchModel = _matchModel;
        view.gameModel = _currentGameModel;
        view.playersArr = _matchModel.others;
        view.owner = _owner;
        view.isEditAction = YES;
        view.actionModel = am;
        
        view.selectedPlayerArr = [NSMutableArray arrayWithArray: am.targetsArr];
        view.selectedAttributeArr = [NSMutableArray arrayWithArray:am.attributesArr];
        view.controlType = [am.actionType isEqualToString:@"杠"]?ControlTypeGang:[am.actionType isEqualToString:@"胡"]?ControlTypeHu:ControlTypeCha;
        
        NSMutableArray *tmp = [NSMutableArray new];
        if ([am.actionType isEqualToString:@"杠"]) {
            [tmp addObjectsFromArray:_patternModel.gangPatternArr];
        }else if ([am.actionType isEqualToString:@"胡"]) {
            [tmp addObjectsFromArray:_patternModel.huPatternArr];
            [tmp addObjectsFromArray:_matchModel.optionalArr];
        }else{
            [tmp addObjectsFromArray:_patternModel.chaPatternArr];
            for (NSString *str in _matchModel.optionalArr) {
                if ([_patternModel.optionalChaPatternArr containsObject:str]) {
                    [tmp addObject:str];
                }
            }
        }
        view.dataArr = tmp;
        if ([am.actionType isEqualToString:@"杠"]) {
            view.collectionView.contentInset = UIEdgeInsetsMake(100, 0, 0, 0);
        }
        [self showModalWithView:view];
    };
    
    return cell;
}
#pragma mark - UICollectionViewDelegate

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(_gameCollectionView.frame.size.width,_gameCollectionView.frame.size.height);
}
//section的内边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

//section之间的行距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
//item之间的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == _gameCollectionView) {
        NSIndexPath *firstIndexPath = [[collectionView indexPathsForVisibleItems] firstObject];
        _gameIndexLabel.text = NSStringFormat(@"第%ld局",firstIndexPath.row + 1);
        _currentGameModel = _gameArr[firstIndexPath.row];
        _indexOfGame = firstIndexPath.row;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
